﻿using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace LD
{
    public partial class FrmLog : FrmBase
    {
        private string logDirectory = Path.Combine(Appbus.BasePath, "Logs");

        public FrmLog()
        {
            InitializeComponent();
        }

        private void FrmLog_Load(object sender, EventArgs e)
        {
            this.lklab_data.Text = "数据目录:" + Path.Combine(Appbus.BasePath, "Data");
            this.lklab_data.Tag = Path.Combine(Appbus.BasePath, "Data");

            DirectoryInfo directoryInfo = new DirectoryInfo(logDirectory);

            if (directoryInfo.Exists)
            {
                TreeNode rootNode = new TreeNode("Logs");
                tv_fileDir.Nodes.Add(rootNode);

                // 遍历日志文件目录
                TraverseDirectory(directoryInfo, rootNode);
            }
        }

        private void TraverseDirectory(DirectoryInfo directory, TreeNode parentNode)
        {
            foreach (var subdirectory in directory.GetDirectories())
            {
                TreeNode directoryNode = new TreeNode(subdirectory.Name);
                directoryNode.Tag = subdirectory.FullName;
                parentNode.Nodes.Add(directoryNode);

                TraverseDirectory(subdirectory, directoryNode);
            }

        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            this.tv_file.Nodes.Clear();

            TreeNode selectedNode = e.Node;

            if (selectedNode.Nodes.Count == 0)
            {
                foreach (var file in Directory.GetFiles(selectedNode.Tag.ToString()))
                {
                    TreeNode fileNode = new TreeNode(file);
                    fileNode.Text = Path.GetFileName(file);
                    fileNode.Tag = file;
                    this.tv_file.Nodes.Add(fileNode);
                }
            }
        }
        private void tv_file_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var selectNode = e.Node;
            if (File.Exists(selectNode.Tag.ToString()))
            {
                StringBuilder sb = new StringBuilder();

                using (FileStream reader = new FileStream(selectNode.Tag.ToString(), FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    int fsLen = (int)reader.Length;
                    byte[] heByte = new byte[fsLen];
                    reader.Read(heByte, 0, heByte.Length);
                    reader.Close();

                    string myStr = Encoding.Default.GetString(heByte);
                    sb.AppendLine(myStr);
                }
                this.txt_log.Text = sb.ToString(); ;
            }
        }

        private void lklab_data_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(this.lklab_data.Tag.ToString());
        }
    }
}
